export interface CalculationHistoryItem {
  id: string;
  title: string; // human readable title for the calculation card
  calculationType: string; // type key used to run calculation
  params: any; // input params saved from the form
  results: any; // structured results (array or object) - keep as any so callers can provide formatter output
  timestamp: number;
}

export const HISTORY_KEY = 'calculationHistory';

export function getHistory(): CalculationHistoryItem[] {
  try {
    const raw = localStorage.getItem(HISTORY_KEY);
    const allHistory = raw ? JSON.parse(raw) : [];
    
    // 从用户设置中读取历史记录最大数量，默认为20
    let maxCount = 20;
    const appSettings = localStorage.getItem('appSettings');
    if (appSettings) {
      try {
        const settings = JSON.parse(appSettings);
        if (settings.historyMaxCount && typeof settings.historyMaxCount === 'number') {
          maxCount = settings.historyMaxCount;
        }
      } catch (parseError) {
        console.error('Failed to parse appSettings:', parseError);
      }
    }
    
    // 只返回用户设置的最大数量的记录
    return allHistory.slice(0, maxCount);
  } catch (err) {
    console.error('getHistory failed', err);
    return [];
  }
}

export function saveHistoryItem(item: CalculationHistoryItem) {
  try {
    // 从用户设置中读取历史记录最大数量，默认为20
    let maxCount = 20;
    const appSettings = localStorage.getItem('appSettings');
    if (appSettings) {
      try {
        const settings = JSON.parse(appSettings);
        if (settings.historyMaxCount && typeof settings.historyMaxCount === 'number') {
          maxCount = settings.historyMaxCount;
        }
      } catch (parseError) {
        console.error('Failed to parse appSettings:', parseError);
      }
    }
    
    // 直接从localStorage读取所有历史记录，避免重复截断
    const raw = localStorage.getItem(HISTORY_KEY);
    const allHistory = raw ? JSON.parse(raw) : [];
    
    // 在列表开头添加新记录
    allHistory.unshift(item);
    
    // 只保留用户设置的最大数量的记录
    const trimmed = allHistory.slice(0, maxCount);
    localStorage.setItem(HISTORY_KEY, JSON.stringify(trimmed));
  } catch (err) {
    console.error('saveHistoryItem failed', err);
  }
}

export function clearHistory() {
  try {
    localStorage.removeItem(HISTORY_KEY);
  } catch (err) {
    console.error('clearHistory failed', err);
  }
}
